package com.kongwg.Java2;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author kongwg
 * @create 2020-12-17 15:05
 */
public class GenericTest {



    @Test
    public void test1(){
        //继承关系
        ArrayList<String> list1 = null;
        ArrayList<Integer> list2 = null;
        //no
//        list1 = list2;

        List<String> l1 = null;
        ArrayList<String> l2 = null;
        //yes
        l1 = l2;

    }

    @Test
    public void test2(){
        //通配符的使用
        ArrayList<String> list1 = null;
        ArrayList<Object> list2 = null;

        List<?> list = null;

        list = list1;
        list = list2;

//        print(list1);
//        print(list2);

        List<String> list3 = new ArrayList<>();
        list3.add("AA");
        list3.add("BB");
        list3.add("CC");

        list = list3;

//        list.add("DD");

        list.add(null);

        //读取
        Object o = list.get(0);
        System.out.println(o);
    }


    public void print(List<?> list){
        Iterator<?> iterator = list.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            System.out.println(obj);
        }
    }

    /**
     * 有限制条件的通配符
     * ? extends A
     * ? super A
     */

    @Test
    public void test3(){
        List<? extends Person> list1 = null;
        List<? super Person> list2 = null;

        List<Student> list3 = new ArrayList<Student>();
        List<Person> list4 = new ArrayList<Person>();
        List<Object> list5 = new ArrayList<Object>();

        list1 = list3;
        list1 = list4;
//        list1 = list5;
//
//        list2 = list3;
        list2 = list4;
        list2 = list5;

        //读数据
        list1 = list4;
        Person person = list1.get(0);

        list2 = list4;
        Object object = list2.get(0);


//        list1.add(new Person());
//        list2.add(new Object());
        list1.add(null);
        list2.add(new Student());
        list2.add(new Person());
    }
}
